package cqie.personal.frame.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import cqie.personal.frame.entity.UserInfo;
import cqie.personal.frame.enums.Code;
import cqie.personal.frame.exception.ValidationFailException;
import cqie.personal.frame.mapper.UserInfoMapper;
import cqie.personal.frame.service.impl.UploadDownloadServiceImpl;
import cqie.personal.frame.util.JwtUtil;
import cqie.personal.frame.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Api(tags = "文件上传下载")
@Controller
public class UploadDownloadController {

    @Resource
    UploadDownloadServiceImpl service;
    @Resource
    UserInfoMapper userInfoMapper;

    @ApiOperation("上传")
    @PostMapping("**/upload")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_UNCOMMITTED)
    public ResultVO importTimeCardTo(@RequestBody MultipartFile file ,HttpServletRequest request) throws ValidationFailException {
        String token = request.getHeader("token");
        if (file.isEmpty()) {
            return new ResultVO(Code.OPERATION_FAIL.getCode(), Code.OPERATION_FAIL.getMessage());
        }
        String url = service.upload(file);
        if (url==null) {
            return new ResultVO(Code.OPERATION_FAIL.getCode(), Code.OPERATION_FAIL.getMessage());
        }
        UserInfo user = JwtUtil.parsingToken(token);
        UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",user.getId());
        updateWrapper.set("user_img",url);

        if(userInfoMapper.update(null,updateWrapper)!=1){
            return new ResultVO(Code.OPERATION_FAIL.getCode(), Code.OPERATION_FAIL.getMessage());
        }
        return new ResultVO();
    }

}